package main

import (
	"flag"
	"fmt"
	"net/http"
	"path/filepath"
	"strings"

	"mall/service/attachment/api/internal/config"
	"mall/service/attachment/api/internal/handler"
	"mall/service/attachment/api/internal/svc"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/attachment.yaml", "the config file")

func dirhandler(pattern string, fileDir string) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		handler := http.StripPrefix(pattern, http.FileServer(http.Dir(fileDir)))
		handler.ServeHTTP(w, r)
	}
}

func staticFileHandler(engine *rest.Server, svcCtx *svc.ServiceContext) {
	dirLevel := []string{":1", ":2", ":3", ":4", ":5", ":6", ":7", ":8"}
	pattern := "/static/"
	uploadPath := filepath.Dir(filepath.Dir(svcCtx.Config.NfsConf.UploadPath))
	for i := 1; i < len(dirLevel); i++ {
		path := "/" + strings.Join(dirLevel[:i], "/")
		engine.AddRoute(
			rest.Route{
				Method:  http.MethodGet,
				Path:    path,
				Handler: dirhandler(pattern, uploadPath),
			})
	}
}

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)

	ctx := svc.NewServiceContext(c)
	// server := rest.MustNewServer(c.RestConf)
	// 跨域这事应该在nginx上做的
	server := rest.MustNewServer(c.RestConf, rest.WithCors())
	defer server.Stop()

	staticFileHandler(server, ctx)

	handler.RegisterHandlers(server, ctx)

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
